home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9556 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: newsfeed.internetmci.com!xmission!news
  2. From: tknarr@xmission.com    ( Todd Knarr )
  3. Newsgroups: comp.lang.c++,rb.technical
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Date: 2 Mar 1996 18:16:59 GMT
  6. Organization: Chaos Central
  7. Message-ID: <4ha3ar$neq@news.xmission.com>
  8. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <4h525l$pja@rap.SanDiegoCA.ATTGIS.COM>
  9. Reply-To: tknarr@xmission.com   ( Todd Knarr )
  10. NNTP-Posting-Host: slc139.xmission.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4h525l$pja@rap.SanDiegoCA.ATTGIS.COM>, dle@costello.SanDiegoCA.ATTGIS.COM (Jake Le) writes:
  14. >You can call the operator= in your copy constructor.
  15.  
  16. This is true, but in classes with more complex internal structure you
  17. probably don't want to do it. When operator= is used, it may need to
  18. undo parts of an initialized object ( freeing allocated memory and the
  19. like ) before it can do the assignment. If used within the copy ctor,
  20. the target will not be initialized unless you take care to initialize
  21. it first ( most of the time you don't ). If part of operator= involves
  22. deleting memory pointed to by a data member and that data member contains
  23. random numbers because it wasn't ever initialized, the results will be
  24. unpleasant.
  25.  
  26. I tend to break it down into three routines. One is a private routine
  27. that just does the "copy an object into the target" part. The copy ctor
  28. can just call this routine directly. operator= does whatever is needed
  29. to prepare the target for overwriting, then calls the routine to do the
  30. copying.
  31.  
  32. --
  33. Todd Knarr : tknarr@xmission.com      |  finger for PGP public key
  34.                                       |  Member, USENET Cabal
  35.  
  36. Seriously, I don't want to die just yet.  I don't care how
  37. good-looking they are, I! don't! want! to! die!"
  38.                                         -- Megazone ( UF1 )
  39.  
  40.